package com.imooc.threadexample;

/**
 * Created by yijy on 2017/11/16.
 */
public class EnergySystem {

    private static double[] energyBox;

    private static Object obj = new Object();

    public EnergySystem(int n,double initEnergy){
        energyBox = new double[n];
        for(int i=0;i<n;i++ )
            energyBox[i] = initEnergy;
    }

    public void transferEnergy(int from ,int to, double amount){
        synchronized (obj){
            while (energyBox[from]<amount){
                try {
                    obj.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.print(Thread.currentThread().getName());
            energyBox[from] -= amount;
            System.out.printf("从第%d号盒子转移能量 %5.2f到第%d号盒子\t",from,amount,to);
            energyBox[to] += amount;
            System.out.printf("总能量 %10.2f",sumEnergy());
            System.out.println();
            obj.notifyAll();
        }
    }

    public double sumEnergy(){
        double sum=0;
        for(double amount : energyBox)
            sum += amount;
        return sum;
    }

    public int getEnergyLength(){
        return energyBox.length;
    }

}
